package java21demo;

import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class VirtualThreadTest {
    public static final int N = 10_0000;
    public static final int TIMEOUT = 100; // 100秒的超时时间

    public static void traditionalThreadTest() throws InterruptedException {
        System.out.println("Traditional Thread Test Begin:");
        Instant startTime;
        try (ExecutorService executor = Executors.newCachedThreadPool()) {
            startTime = Instant.now();
            for (int i = 0; i < N; i++) {
                executor.execute(() -> {
                    try {
                        Thread.sleep(1000); // 休眠1秒
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
            }
            executor.shutdown();
            // TIMEOUT秒以后线程池的任务仍未全部执行完毕，则立即关闭线程池并尝试中断所有正在执行的任务
            if (!executor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        }

        Instant endTime = Instant.now();
        long duration = endTime.toEpochMilli() - startTime.toEpochMilli();
        System.out.println("All threads have finished.");
        System.out.println("Duration: " + duration + " milliseconds");
    }

    public static void virtualThreadTest() throws InterruptedException {
        System.out.println("Virtual Thread Test Begin:");
        Instant startTime;
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            startTime = Instant.now();
            for (int i = 0; i < N; i++) {
                executor.execute(() -> {
                    try {
                        Thread.sleep(1000); // 休眠1秒
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
            }
            executor.shutdown();
            if (!executor.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        }
        Instant endTime = Instant.now();
        long duration = endTime.toEpochMilli() - startTime.toEpochMilli();
        System.out.println("All virtual threads have finished.");
        System.out.println("Duration: " + duration + " milliseconds");
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("Total: "+ N +" tasks!");
        System.out.println("----------------------");
        virtualThreadTest();
        System.out.println("----------------------");
        traditionalThreadTest();
    }
}
